﻿using System;
using System.Windows.Input;
using Utils.Wpf;

namespace StockAnalyst2.Chart
{
	internal class OptionsVM : ViewModelBase
	{
		#region Attributes

		private readonly Options _model;
		private readonly Options _currentOptions;

		#endregion

		#region Properties

		public ChartOptionsVM Options { get; private set; }

		public ICommand AcceptCommand { get; private set; }
		public ICommand CancelCommand { get; private set; }

		#endregion

		#region Events

		public event EventHandler<DialogCloseRequestedEventArgs> DialogCloseRequested;

		#endregion

		#region Public Methods

		public OptionsVM(Options model)
		{
			_model = model;
			_currentOptions = _model.Clone();

			this.Options = new ChartOptionsVM(_currentOptions);
			
			this.AcceptCommand = new DelegateCommand(this.ExecuteAccept, this.CanExecuteAccept);
			this.CancelCommand = new DelegateCommand(this.ExecuteCancel);
		}

		protected virtual void OnDialogCloseRequested(bool? result)
		{
			if (this.DialogCloseRequested != null)
			{
				this.DialogCloseRequested(this, new DialogCloseRequestedEventArgs(result));
			}
		}

		#endregion

		#region Private Methods

		private void ExecuteAccept()
		{
			_model.Copy(_currentOptions);

			this.OnDialogCloseRequested(true);
		}

		private bool CanExecuteAccept()
		{
			return !this.Options.LastValueVM.HasValidationErrors && !this.Options.BidAskAverageVM.HasValidationErrors && !this.Options.BidVM.HasValidationErrors && !this.Options.AskVM.HasValidationErrors && !this.Options.SMA1VM.HasValidationErrors && !this.Options.SMA2VM.HasValidationErrors && !this.Options.SMA3VM.HasValidationErrors && !this.Options.StochasticVM.HasValidationErrors && !this.Options.VolumeVM.HasValidationErrors && !this.Options.TotalVolumeVM.HasValidationErrors;
		}

		private void ExecuteCancel()
		{
			this.OnDialogCloseRequested(false);
		}

		#endregion
	}
}
